<template>
  <el-cascader v-bind="attrs" v-on="$listeners" @change="handleChange"></el-cascader>
</template>

<script>
const isEqual = (a, b) => {
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return false
    }

    for (let i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) {
        return false
      }
    }

    return true
  }

  return a === b
}

export default {
  components: {},
  props: {},
  data() {
    return {
      checkedValue: this.$attrs.value,
    }
  },
  computed: {
    props() {
      return Object.assign(
        {
          multiple: false,
          lazy: false,
          checkStrictly: true,
        },
        this.$attrs.props
      )
    },
    attrs() {
      return Object.assign(this.$attrs, {
        props: { ...this.props },
        popperClass: 'c-cascader__hide-radio',
      })
    },
    cascaderRef() {
      return this.$children[0]
    },
    panel() {
      return (this.cascaderRef && this.cascaderRef.panel) || {}
    },
  },
  watch: {
    '$attrs.value'(val) {
      if (isEqual(val, this.checkedValue)) return
      this.checkedValue = val
      this.props.lazy ? this.refreshNodes() : this.refreshExpand()
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleChange(val) {
      this.checkedValue = val

      const { props } = this
      if (props.multiple) {
        return
      }

      const node = this.getCheckedNode()
      if (!node) {
        return
      }

      if (!node.hasChildren) {
        return this.toggleDropDownVisible(false)
      }

      if (props.lazy && !node.loaded) {
        this.panel.lazyLoad(node)
      }
    },

    getCheckedNode() {
      const nodes = this.getCheckedNodes()
      const nodeCount = nodes && nodes.length
      if (!nodeCount) {
        return
      }

      return nodes[nodeCount - 1]
    },

    clearCheckedNodes() {
      return this.panel.clearCheckedNodes()
    },

    getCheckedNodes() {
      return this.cascaderRef.getCheckedNodes()
    },

    toggleDropDownVisible(visible) {
      this.cascaderRef.toggleDropDownVisible(visible)
    },

    refreshNodes() {
      this.$nextTick(() => {
        this.panel.loadCount = 0
        this.panel.lazyLoad()
      })
    },

    refreshExpand() {
      this.$nextTick(() => {
        const nodes = (this.getCheckedNodes()[0] || {}).pathNodes
        nodes && nodes.length && this.panel.expandNodes(nodes)
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
